package com.example.activiti.common;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 节点相关的功能
 * @author zjh
 *
 */
@Service
public class ActiveNoticeInfo {
	@Autowired
	private TaskService taskService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private RepositoryService repositoryService;
	
	
	/**
	 * 获取下一节点
	 * @param processInstanceId
	 * @return
	 */
	public UserTask getNextUserFlowElement(String processInstanceId){
        Task task=taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
        if (task==null){
            throw new RuntimeException("流程未启动或已执行完成");
        }
        // 取得已提交的任务
        HistoricTaskInstance historicTaskInstance = historyService
        		.createHistoricTaskInstanceQuery()
                .taskId(task.getId()).singleResult();
        // 取得正在流转的流程实例,若已完成则为null
        //获得流程定义
        ProcessDefinition processDefinition=repositoryService.getProcessDefinition(historicTaskInstance.getProcessDefinitionId());
        //获得当前流程的活动ID
        Execution execution = runtimeService
        		.createExecutionQuery()
        		.executionId(historicTaskInstance.getExecutionId())
        		.singleResult();
        String activityId=execution.getActivityId();
        UserTask userTask =null;
        while (true){
            //根据活动节点获取当前的组件信息
            FlowNode flowNode =getFlowNode(processDefinition.getId(),activityId);
            SequenceFlow sequenceFlow = flowNode.getIncomingFlows().get(0);
        	//获取上一节点
        	FlowElement beforeElement = sequenceFlow.getSourceFlowElement();
        	//获取下一节点
        	FlowElement nextElement = sequenceFlow.getTargetFlowElement();
        	userTask = (UserTask) nextElement;
            return userTask;
        }
 
    }
	
    /**
     * 根据活动节点和流程定义ID获取该活动节点的组件信息
     * @param processDefinitionId
     * @param activityId
     * @return
     */
    public FlowNode getFlowNode(String processDefinitionId,String activityId){
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
        FlowNode flowNode = (FlowNode) bpmnModel.getMainProcess().getFlowElement(activityId);
        return flowNode;
    }
}
